// @ts-nocheck

import qs from 'qs'
import {
  getUserInfo,
  login,
  miniTenantChange,
  loginByCode,
  bindAppIdApi
} from '@/api/user'
import { encryption, generateUniqueRandomString } from '@/utils/index'
import { clearStorage } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    /** 用户信息 */
    user: {},
    userInfo: uni.getStorageSync('userInfo')
      ? JSON.parse(uni.getStorageSync('userInfo'))
      : { sysUser: {} },
    token: uni.getStorageSync('token') || '',
    isSubscribe: uni.getStorageSync('isSubscribe') || false,
    equipment: uni.getStorageSync('equipment') || undefined
  },
  getters: {
    username: (state) => state.userInfo.sysUser.username,
    phone: (state) => state.userInfo.sysUser.phone
  },
  mutations: {
    SET_USERINFO: (state, payload) => {
      state.userInfo = payload
      uni.setStorageSync('userInfo', JSON.stringify(payload))
    },
    SET_TOKEN(state, payload) {
      state.token = payload
      uni.setStorageSync('token', payload)
    },
    SET_IS_SUBSCRIBEl(state, type) {
      state.isSubscribe = type
      uni.setStorageSync('isSubscribe', type)
    },
    INIT_EQUIPMENT: (state) => {
      if (!state.equipment) {
        const code = generateUniqueRandomString()
        state.equipment = code
        uni.setStorageSync('equipment', code)
      }
    }
  },
  actions: {
    /** 登录 */
    // eslint-disable-next-line consistent-return
    login: async ({ commit, dispatch, state }, { type, ...data }) => {
      // eslint-disable-next-line no-async-promise-executor, consistent-return
      return new Promise(async (resolve, reject) => {
        const params = {
          username: data.username,
          password: data.password,
          supplier_code: data.supplierCode,
          equipment: state.equipment
        }
        if (data.code) {
          params.code = data.code
          params.phone = data.phone
        }
        const dataObj = encryption({
          data: params,
          key: 'pigxpigxpigxpigx',
          param: ['password']
        })
        const dataObjs = qs.stringify(dataObj)
        let res
        if (data.loginType === 'byCode') {
          res = await loginByCode(
            data.phone,
            data.code,
            `${type}`.toUpperCase(),
            state.equipment
          ).catch(reject)
        } else {
          res = await login(dataObjs, type).catch(reject)
        }

        if (['更换设备登录需要手机验证码校验'].includes(res?.msg)) {
          return reject(res)
        }
        if (!res?.identity) {
          return reject(res)
        }
        const identity = res.identity.split(',')
        if (type === 'CUSTOMER' && !identity.includes('CUSTOMER')) {
          reject(res)
          uni.showToast({
            title: '该用户没有访问权限',
            duration: 2000,
            icon: 'none'
          })
          return false
        }
        if (type === 'SUPPLIER' && !identity.includes('SUPPLIER')) {
          reject(res)
          uni.showToast({
            title: '该用户没有访问权限',
            duration: 2000,
            icon: 'none'
          })
          return false
        }

        if (res) {
          uni.setStorageSync('token', `${res.token_type} ${res.access_token}`)
          uni.setStorageSync('tenant_id', `${res.tenant_id}`)
          const userInfo = await getUserInfo()
          uni.login({
            success(result) {
              bindAppIdApi({
                userId: userInfo.data.sysUser.userId,
                code: result.code
              })
            }
          })
          commit('SET_USERINFO', userInfo.data)
          if (userInfo.data.sysUser.supplierCode) {
            uni.setStorageSync(
              'supplier_code',
              userInfo.data.sysUser.supplierCode
            )
          }
          if (type === 'SUPPLIER') {
            data.subscribe(false)
          } else {
            data.selectTenant()
          }
        }
        resolve(res)
      })
    },
    /** 登出 */
    logout: async () => {
      clearStorage()
      uni.reLaunch({ url: '/pages/login/index' })
    },
    /** 获取用户额外信息 */
    getUserExt: async ({ commit }) => {
      const userInfo = await getUserInfo()
      commit('SET_USERINFO', userInfo.data)
    },
    // 切换租户
    checkTenant: async ({ dispatch, commit, state }, { username, type }) => {
      const res = await miniTenantChange(username, type, state.equipment)
      commit('SET_TOKEN', `${res.token_type} ${res.access_token}`)
      uni.setStorageSync('tenant_id', `${res.tenant_id}`)
      await dispatch('getUserInfo')
    },
    // 获取用户信息
    getUserInfo: async ({ commit }) => {
      const userInfo = await getUserInfo()
      commit('SET_USERINFO', userInfo.data)
      if (userInfo.data.sysUser.supplierCode) {
        uni.setStorageSync('supplier_code', userInfo.data.sysUser.supplierCode)
      }
    }
  }
}
